
from pyecharts import options as opts
from pyecharts.charts import Kline
import baostock as bs
import pandas as pd

lg = bs.login()
# 显示登陆返回信息
print('login respond error_code:'+lg.error_code)
print('login respond  error_msg:'+lg.error_msg)

#### 获取历史K线数据 ####
# 详细指标参数，参见“历史行情指标参数”章节
rs = bs.query_history_k_data_plus("sh.600000",
    "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
    start_date='2023-01-01', end_date='2023-12-31',
    frequency="d", adjustflag="3") #frequency="d"取日k线，adjustflag="3"默认不复权
print('query_history_k_data_plus respond error_code:'+rs.error_code)
print('query_history_k_data_plus respond  error_msg:'+rs.error_msg)

#### 打印结果集 ####
data_list = []
while (rs.error_code == '0') & rs.next():
    # 获取一条记录，将记录合并在一起
    data_list.append(rs.get_row_data())
stock_data = pd.DataFrame(data_list, columns=rs.fields)

# k线数据
kline_data = []
for index, row in stock_data.iterrows():
  kline_data.append([row['open'], row['close'], row['low'], row['high']])

# 配置 Kline 图
kline = (
  Kline()
  .add_xaxis(xaxis_data=stock_data['date'].to_list())
  .add_yaxis(series_name="日K线", y_axis=kline_data)
  .set_global_opts(
    xaxis_opts=opts.AxisOpts(is_scale=True),
    yaxis_opts=opts.AxisOpts(is_scale=True),
    title_opts=opts.TitleOpts(title="浦发银行日k线"),
    datazoom_opts=[opts.DataZoomOpts()],
    toolbox_opts=opts.ToolboxOpts(
      feature={
        "dataZoom": {"yAxisIndex": "none"},
        "restore": {},
        "saveAsImage": {},
      }
    ),
  )
)

# 渲染图表
kline.render("kline_chart.html")



bs.logout()